<!DOCTYPE html>
<html>
  <head>
    <title>
      dynamicscompressor-simple.html
    </title>
    <script src="../../resources/testharness.js"></script>
    <script src="../../resources/testharnessreport.js"></script>
    <script src="../resources/audit-util.js"></script>
    <script src="../resources/audit.js"></script>
  </head>
  <body>
    <script id="layout-test-code">
      let audit = Audit.createTaskRunner();
      let context;
      let compressor;
      let sampleRate = 44100;
      let lengthInSeconds = 1;
      let renderedData;
      // This threshold experimentally determined. It depends on the the gain
      // value of the gain node below and the dynamics compressor.  When the
      // DynamicsCompressor had the pre-emphasis filters, the peak value is
      // about 0.21.  Without it, the peak is about 0.84.
      let peakThreshold = 0.83;

      function checkResult(renderedBuffer, should) {
        renderedData = renderedBuffer.getChannelData(0);
        // Search for a peak in the last part of the data.
        let startSample = sampleRate * (lengthInSeconds - .1);
        let endSample = renderedData.length;
        let k;
        let peak = -1;

        for (k = startSample; k < endSample; ++k) {
          let sample = Math.abs(renderedData[k]);
          if (peak < sample)
            peak = sample;
        }

        should(peak >= peakThreshold, 'Pre-emphasis effect not applied')
            .beTrue();

        should(compressor.reduction !== 0, 'Reduction value changed').beTrue();
      }

      audit.define(
          {
            label: 'test',
            description: 'Test pre-emphasis in DynamicsCompressor is removed'
          },
          function(task, should) {

            context = new OfflineAudioContext(
                1, sampleRate * lengthInSeconds, sampleRate);
            // Connect an oscillator to a gain node to the compressor.  The
            // oscillator frequency is set to a high value for the (original)
            // emphasis to kick in. The gain is a little extra boost to get the
            // compressor enabled.
            //
            let osc = context.createOscillator();
            osc.frequency.value = 15000;
            let gain = context.createGain();
            gain.gain.value = 1.5;
            compressor = context.createDynamicsCompressor();
            osc.connect(gain);
            gain.connect(compressor);
            compressor.connect(context.destination);
            osc.start();

            context.startRendering()
                .then(buffer => checkResult(buffer, should))
                .then(() => task.done());
            ;
          });

      audit.run();
    </script>
  </body>
</html>
